//
//  QSProblemReportFirstCell.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/25.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSProblemReportFirstCell.h"
#import "BRPickerView.h"
#import "QSSelectImageCell.h"
static NSString *holderText = @"  请输入问题标题";

static NSString *defaultCell = @"DefaultCell";
static NSString *selectPhotoCell = @"SelectPhotoCell";
@implementation QSProblemReportFirstCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [self configSubView];
    [self configCollectinoView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)configSubView{
    self.backgroundColor = [UIColor clearColor];
    self.contentView.layer.cornerRadius = 8;
    self.contentView.layer.masksToBounds = YES;
    self.contentView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.mas_leading).offset(kRealValue(10));
        make.trailing.equalTo(self.mas_trailing).offset(kRealValue(-10));
        make.top.equalTo(self.mas_top).offset(kRealValue(2));
        make.bottom.equalTo(self.mas_bottom).offset(kRealValue(0));
    }];
    
    self.selectActionLabel.layer.cornerRadius = 5;
    self.selectActionLabel.layer.borderColor = [UIColor QSColorGrayEAEAEA].CGColor;
    self.selectActionLabel.layer.borderWidth = 0.5;
    self.selectActionLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectProblemAction:)];
    [self.selectActionLabel addGestureRecognizer:tap];
    
    self.describeTextView.layer.cornerRadius = 5;
    self.describeTextView.layer.borderColor = [UIColor QSColorGrayEAEAEA].CGColor;
    self.describeTextView.layer.borderWidth = 0.5;
    self.describeTextView.delegate = self;
    
    self.titleTextField.layer.cornerRadius = 5;
    self.titleTextField.layer.borderColor = [UIColor QSColorGrayEAEAEA].CGColor;
    self.titleTextField.layer.borderWidth = 0.5;
    self.titleTextField.delegate = self;
    self.titleTextField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:holderText attributes:@{NSFontAttributeName:[UIFont QSFontOfSize12]}];
    self.titleTextField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:holderText attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
    
    [_typeLabel setAttributedText:[UILabel setLabelTextColorWithString:_typeLabel.text Range:NSMakeRange(4, 1) andColor:[UIColor redColor]]];
    [_titleLabel setAttributedText:[UILabel setLabelTextColorWithString:_titleLabel.text Range:NSMakeRange(4, 1) andColor:[UIColor redColor]]];
    [_describeLabel setAttributedText:[UILabel setLabelTextColorWithString:_describeLabel.text Range:NSMakeRange(4, 1) andColor:[UIColor redColor]]];
}
//添加的时候重新赋值
- (void)initView{
        self.typeLabel.text = @"请选择问题类型";
        self.titleLabel.text = @"请输入问题标题";
        self.describeTextView = nil;
        self.picArr = [NSMutableArray array];
        [self.collectionView reloadData];
}


- (void)layoutSubviews{
    self.describeTextView.placeholder = @"请输入问题描述";
    if (self.type == 1) {
        self.deletButton.hidden = NO;
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.mas_leading).offset(kRealValue(0));
            make.trailing.equalTo(self.mas_trailing).offset(kRealValue(0));
            make.top.equalTo(self.mas_top).offset(kRealValue(10));
            make.bottom.equalTo(self.mas_bottom).offset(kRealValue(0));
        }];
    }else{
        self.deletButton.hidden = YES;
//        self.maxNum = 9;
    }
    self.maxNum = 6;
}
- (void)selectProblemAction:(UITapGestureRecognizer *)sender{
    if (self.problemTypeArr.count) {
            NSMutableArray *copyCompanyArr = [NSMutableArray array];
            for (NSDictionary *dic in self.problemTypeArr) {
                NSString *companyName = [dic objectForKey:@"ptName"];
                [copyCompanyArr addObject:companyName];
            }
            [BRStringPickerView showStringPickerWithTitle:@"请选择问题类型" dataSource:copyCompanyArr defaultSelValue:nil resultBlock:^(id selectValue) {
                for (NSDictionary *dic in self.problemTypeArr) {
                    if ([dic[@"ptName"] isEqualToString:selectValue]) {
                        self.selectActionLabel.text = selectValue;
                        self.model.problemName = selectValue;
                        //取出问题名字 类型id赋值
                        if (self.didSelectProblemTypeFinish) {
                            self.didSelectProblemTypeFinish(selectValue, dic[@"ptId"]);
                        }
                        break;
                    }
                }
            }];
        }else{
            [QSAppKeyWindow showAutoHideHudWithText:@"没有获取到的数据!"];
        }
}
#pragma mark - TextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView{
    if (self.didDescriptionInputFinish) {
        self.didDescriptionInputFinish(textView.text);
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (text.length == 0) return YES;//允许删除。
    if (textView.text.length >= 180) {
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - TextFieldDelegaete
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (self.didTitleInputFinish) {
        self.didTitleInputFinish(textField.text);
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (string.length == 0) return YES;//允许删除。

    if (textField.text.length >= 25) {
        return NO;
    }else{
        return YES;
    }
}

- (void)configCollectinoView{
    UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc]init];
    flowLaout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //上下间距
        flowLaout.minimumLineSpacing = 15;
    //左右间距
        flowLaout.minimumInteritemSpacing = 15.5;
    self.collectionView.collectionViewLayout = flowLaout;
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:defaultCell];
    [self.collectionView registerClass:[QSSelectImageCell class] forCellWithReuseIdentifier:selectPhotoCell];

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
//    [self setupAutoHeightWithBottomView:self.collectionVIew bottomMargin:10];

}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.picArr.count == _maxNum) {
        return self.picArr.count;
    }else{
        return _picArr.count + 1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_picArr.count < _maxNum && indexPath.item == self.picArr.count) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:defaultCell forIndexPath:indexPath];
        UIImageView *pic = [[UIImageView alloc]initWithFrame:cell.contentView.frame];
        //    [pic sd_setImageWithURL:[NSURL URLWithString:_picArr[indexPath.item]]];
        pic.image = [UIImage imageNamed:@"icon_addimage"];
        pic.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:pic];
        return cell;
    }else{
        QSSelectImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:selectPhotoCell forIndexPath:indexPath];
        [cell.imagev setImage:self.picArr[indexPath.row]];
        cell.deleteButton.hidden = NO;
        cell.deleteButton.tag = indexPath.item;
        [cell.deleteButton addTarget:self action:@selector(deletePhotos:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_picArr.count < _maxNum && indexPath.item == self.picArr.count)  {
        //小于num 点击到添加
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:_maxNum delegate:self];
        [imagePicker setSortAscendingByModificationDate:NO];
        imagePicker.selectedAssets = _assestArray;
        imagePicker.allowPickingVideo = NO;
        [[UIViewController currentViewController] presentViewController:imagePicker animated:YES completion:nil];
    }else{
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_assestArray selectedPhotos:_picArr index:indexPath.row];
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        }];
        [[UIViewController currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(kRealValue(65), kRealValue(65));
}

//内边距处理
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // UIEdgeInsets insets = {top, left, bottom, right};
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    self.picArr = [NSMutableArray arrayWithArray:photos];
//    [self checkPhotosCountWithAddImage];
    self.assestArray = [NSMutableArray arrayWithArray:assets];
    if (_model) {
        _model.picArr = [NSMutableArray arrayWithArray:photos];
        _model.assetArr = [NSMutableArray arrayWithArray:assets];
    }
    if (photos.count > 0) {
        if (self.didSelectImageFinish) {
            self.didSelectImageFinish(photos);
        }
    }
    [_collectionView reloadData];
}

//删除图片数组的某一张
- (void)deletePhotos:(UIButton *)sender{
    NSLog(@"%ld", self.picArr.count);
    [self.picArr removeObjectAtIndex:sender.tag];
    [self.assestArray removeObjectAtIndex:sender.tag];
    NSArray<UIImage *>* photoArr = self.picArr.copy;
    if (self.didSelectImageFinish) {
        self.didSelectImageFinish(photoArr);
    }
    [self.collectionView reloadData];
    
}
//删除此行问题cell
- (IBAction)deleteProblemButtonAction:(UIButton *)sender {
    if (self.didDeleteProblemBlock) {
        self.didDeleteProblemBlock(sender);
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    for (UIView *view in self.subviews) {
        [view endEditing:YES];
    }
    [self endEditing:YES];
}

- (void)setModel:(QSProblemListModel *)model{
    _model = model;
    if (model.typeId) {
        self.selectActionLabel.text = _model.problemName;
    }else{
        self.selectActionLabel.text = @"请选择问题类型";
    }
    
    if (model.title) {
        self.titleTextField.text = _model.title;
    }else{
        self.titleTextField.text = @"";
    }
    if (model.info) {
        self.describeTextView.text = model.info;

    }else{
        self.describeTextView.text = @"";
    }
    if (model.picArr) {
        self.picArr = model.picArr;
        self.assestArray = model.assetArr;
        [self.collectionView reloadData];
    }
//    else{
//        self.picArr = [NSMutableArray array];
//        [self.collectionView reloadData];
//    }
}

/**
*  键盘即将显示的时候调用
*/
- (void)keyboardWillShow:(NSNotification *)note{
    [[UIViewController currentViewController] keyboardWillShow:note TextY:self.titleTextField.y];
}

/**
 *  键盘即将退出的时候调用
 */
- (void)keyboardWillHide:(NSNotification *)note{
    [[UIViewController currentViewController] keyboardHiden:note];
}
- (void)dealloc{
    //移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
